package com.itstu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itstu.common.utils.HttpUtils;
import com.itstu.gulimall.member.dao.MemberLevelDao;
import com.itstu.gulimall.member.entity.MemberLevelEntity;
import com.itstu.gulimall.member.exception.PhoneExistException;
import com.itstu.gulimall.member.exception.UserNameExistException;
import com.itstu.gulimall.member.vo.MemberLoginVo;
import com.itstu.gulimall.member.vo.MemberRegistVo;
import com.itstu.gulimall.member.vo.SocialUserVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itstu.common.utils.PageUtils;
import com.itstu.common.utils.Query;

import com.itstu.gulimall.member.dao.MemberDao;
import com.itstu.gulimall.member.entity.MemberEntity;
import com.itstu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveRegistVo(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        // 设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        // 检查手机号和用户名是否唯一
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        // 密码要加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setNickname(vo.getUserName());
        baseMapper.insert(memberEntity);

    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException{
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0){
            throw new UserNameExistException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0){
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        // 取数据库查询
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if (entity== null){
            // 登陆失败
            return null;
        }else {
            //
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches){
                return entity;
            }else {
                return null;
            }

        }
    }

    @Override
    public MemberEntity login(SocialUserVo vo) throws Exception {
        // 具有登录和注册合并的逻辑
        String uid = vo.getUid();
        // 判断当前社交用户是否已经登录过系统
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null ){
            // 这个用户已经注册了
            System.out.println("此用户已经注册");
            MemberEntity updateEntity = new MemberEntity();
            updateEntity.setId(memberEntity.getId());
            updateEntity.setAccessToken(vo.getAccess_token());
            updateEntity.setExpiresIn(vo.getExpires_in());
            baseMapper.updateById(updateEntity);
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            return memberEntity;
        }else {
            // 没有查到就要注册
            System.out.println("此用户还未注册");
            MemberEntity regist = new MemberEntity();

            try {
                // 查询当前社交用户的社交账号信息
                Map<String,String> map = new HashMap<>();
                map.put("access_token",vo.getAccess_token());
                map.put("uid",vo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);
                if (response.getStatusLine().getStatusCode() == 200 ){
                    String s = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(s);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    // .....
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender)?1:0);
                    MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
                    regist.setLevelId(levelEntity.getId());
                }
            }catch (Exception e){}
            regist.setSocialUid(vo.getUid());
            regist.setAccessToken(vo.getAccess_token());
            regist.setExpiresIn(vo.getExpires_in());
            baseMapper.insert(regist);
            return regist;
        }

    }

}